import { ref, computed, watch } from 'vue'

export type Theme = 'light' | 'dark'

// Global theme state
const currentTheme = ref<Theme>('dark')

export function useTheme() {
  // Initialize theme from localStorage
  const initializeTheme = () => {
    const savedTheme = localStorage.getItem('fishing-app-theme') as Theme
    if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) {
      currentTheme.value = savedTheme
    } else {
      // Default to system preference
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      currentTheme.value = prefersDark ? 'dark' : 'light'
    }
    applyTheme(currentTheme.value)
  }

  // Apply theme to document
  const applyTheme = (theme: Theme) => {
    document.documentElement.setAttribute('data-theme', theme)
    document.documentElement.className = theme
  }

  // Toggle between themes
  const toggleTheme = () => {
    currentTheme.value = currentTheme.value === 'dark' ? 'light' : 'dark'
  }

  // Set specific theme
  const setTheme = (theme: Theme) => {
    currentTheme.value = theme
  }

  // Computed properties
  const isDark = computed(() => currentTheme.value === 'dark')
  const isLight = computed(() => currentTheme.value === 'light')
  const themeIcon = computed(() => isDark.value ? '☀️' : '🌙')
  const themeLabel = computed(() => isDark.value ? '浅色模式' : '深色模式')

  // Watch for theme changes and persist
  watch(currentTheme, (newTheme) => {
    localStorage.setItem('fishing-app-theme', newTheme)
    applyTheme(newTheme)
  })

  return {
    currentTheme: computed(() => currentTheme.value),
    isDark,
    isLight,
    themeIcon,
    themeLabel,
    toggleTheme,
    setTheme,
    initializeTheme
  }
}